package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itCar.base.tools.IPUtil;
import com.itCar.base.tools.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CityWeather
 * @Description TODO
 * @Author liuzhiguo
 * @Date 2024/8/1 15:14
 * @Version 1.0
 */
@Slf4j
public class CityWeather {
    private static final String apiUrl = "http://t.weather.itboy.net/api/weather/city/";

    public static void main(String[] args) throws IOException {
//        String ip = "113.105.172.33";
//        String cityInfo = IPUtil.getCityInfo(ip);
//        System.out.println(cityInfo);
//        String ipAddress = IPUtil.getIpAddress();
//        String cityCode = fetchCityCode(ipAddress);
//        System.out.println(cityCode);
//        getWeather(cityCode);
//        getIpPossessionByFile(IPUtil.getIpAddress());
    }

    static List<Weather> getWeather(String cityCode) throws IOException {
        //HTTP请求 天气接口
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl + cityCode)
                .build();
        Response response = client.newCall(request).execute();
        //返回
        String strJson = response.body().string();
        //json字符串解析
        JSONObject data = JSON.parseObject(strJson).getJSONObject("data");
        JSONObject cityInfo = JSON.parseObject(strJson).getJSONObject("cityInfo");

        JSONArray forecast = (JSONArray) data.get("forecast");
        //默认该集合中当天数据为集合第0条，所以我只需要将它取出即可。
        String forecast_0 = forecast.get(0).toString();
        //转Weather对象
        Weather weather = JSON.parseObject(forecast_0, Weather.class);
        weather.setCity(cityInfo.getString("city"));
        weather.setTime(JSON.parseObject(strJson).getString("time"));
        weather.setShidu(data.getString("shidu"));
        weather.setQuality(data.getString("quality"));
        weather.setWendu(data.getString("wendu"));

        List<Weather> res = new ArrayList<>();
        res.add(weather);
        System.out.println(res);
        return res;
    }

    private static String fetchCityCode(String ipAddress) {
        ipAddress = "1.199.78.211";
        String urlString = "http://ip-api.com/json/" + ipAddress;
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Accept-Charset", "UTF-8");

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String jsonResponse = response.toString();
                // 解析JSON响应以获取cityCode
                // 这里需要实现解析JSON的逻辑，例如使用第三方库如Jackson或内置的JSON支持
                // 假设JSON格式如下：{"status":"OK","cityCode":"12345"}
                // 你可以使用JSON解析库来获取cityCode
                // String cityCode = parseCityCodeFromJson(jsonResponse);
                // 为了简化示例，我们假设cityCode就是状态为"OK"时的固定值"12345"
                return "OK".equals(parseStatusFromJson(jsonResponse)) ? "12345" : null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String parseStatusFromJson(String json) {
        // 实现JSON解析以获取status字段
        // 这里只是为了示例，直接返回一个固定值
        return "OK";
    }

    public static String XDB_PATH = "E:\\InstallApp\\ChromeDownload\\csdn-ip2region.xdb";
    public static String getIpPossessionByFile(String ip) {
        if (StringUtils.isNotEmpty(ip)) {
            try {
                // 1、创建 searcher 对象
                Searcher searcher = Searcher.newWithFileOnly(XDB_PATH);
                // 2、查询
                long sTime = System.nanoTime();
                String region = searcher.search(ip);
                long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
                region = region.replace("|0", "");
                log.info("{地区: {}, IO操作数: {}, 耗时: {} μs}", region, searcher.getIOCount(), cost);
                return region;
            } catch (Exception e) {
                log.error("获取IP地址异常：{} ", e.getMessage());
                throw new RuntimeException("获取IP地址异常");
            }
        }
        return "未知";
    }

}

